// src/utils/categoryData.js
import { ref } from 'vue'

// 基础分类（不包含设置按钮）- 使用Vant图标
const baseExpenseCategories = [
    { id: 1, name: '餐饮', icon: 'hot-o', color: '#FF6B6B' },
    { id: 2, name: '购物', icon: 'shopping-cart-o', color: '#4ECDC4' },
    { id: 3, name: '日用', icon: 'bag-o', color: '#95E1D3' },
    { id: 4, name: '交通', icon: 'logistics', color: '#F38181' },
    { id: 5, name: '蔬菜', icon: 'flower-o', color: '#A8E6CF' },
    { id: 6, name: '水果', icon: 'smile-o', color: '#FFD93D' }
];

// 收入分类ID与后端保持一致：1=工资，2=兼职，3=理财，4=礼金，5=其他
const baseIncomeCategories = [
    { id: 1, name: '工资', icon: 'balance-pay', color: '#6BCF7F' },
    { id: 2, name: '兼职', icon: 'gold-coin-o', color: '#FFB347' },
    { id: 3, name: '理财', icon: 'chart-trending-o', color: '#4A90E2' },
    { id: 4, name: '礼金', icon: 'gift-o', color: '#FF6B9D' },
    { id: 5, name: '其他', icon: 'balance-o', color: '#B4A7D6' }
];

// 设置按钮（固定不变）
const settingsCategory = { id: 999, name: '设置', icon: 'setting-o', color: '#95A5A6' };

// 加载被删除的基础分类ID
const loadDeletedBaseCategories = () => {
    const deletedExpense = localStorage.getItem('deletedBaseExpenseCategories');
    const deletedIncome = localStorage.getItem('deletedBaseIncomeCategories');

    return {
        expense: deletedExpense ? JSON.parse(deletedExpense) : [],
        income: deletedIncome ? JSON.parse(deletedIncome) : []
    };
};

const loadCategories = () => {
    const savedExpense = localStorage.getItem('customExpenseCategories');
    const savedIncome = localStorage.getItem('customIncomeCategories');
    const deletedBaseCategories = loadDeletedBaseCategories();

    // 过滤掉被删除的基础分类
    const filteredBaseExpense = baseExpenseCategories.filter(cat =>
        !deletedBaseCategories.expense.includes(cat.id)
    );
    const filteredBaseIncome = baseIncomeCategories.filter(cat =>
        !deletedBaseCategories.income.includes(cat.id)
    );

    return {
        expense: [
            ...filteredBaseExpense,
            ...(savedExpense ? JSON.parse(savedExpense) : []),
            settingsCategory
        ],
        income: [
            ...filteredBaseIncome,
            ...(savedIncome ? JSON.parse(savedIncome) : []),
            settingsCategory
        ]
    };
};

const categories = ref(loadCategories());

const saveCategories = () => {
    // 只保存自定义类别，排除基础类别和设置按钮
    const customExpense = categories.value.expense.filter(cat =>
        !baseExpenseCategories.some(base => base.id === cat.id) && cat.id !== 999
    );
    const customIncome = categories.value.income.filter(cat =>
        !baseIncomeCategories.some(base => base.id === cat.id) && cat.id !== 999
    );

    localStorage.setItem('customExpenseCategories', JSON.stringify(customExpense));
    localStorage.setItem('customIncomeCategories', JSON.stringify(customIncome));
};

// 保存被删除的基础分类ID
const saveDeletedBaseCategories = (type, categoryId) => {
    const deletedBaseCategories = loadDeletedBaseCategories();

    if (type === 'expense') {
        if (!deletedBaseCategories.expense.includes(categoryId)) {
            deletedBaseCategories.expense.push(categoryId);
        }
    } else if (type === 'income') {
        if (!deletedBaseCategories.income.includes(categoryId)) {
            deletedBaseCategories.income.push(categoryId);
        }
    }

    localStorage.setItem('deletedBaseExpenseCategories', JSON.stringify(deletedBaseCategories.expense));
    localStorage.setItem('deletedBaseIncomeCategories', JSON.stringify(deletedBaseCategories.income));
};

// 添加自定义分类（自动插入到设置按钮之前）
const addCustomCategory = (type, category) => {
    if (!['expense', 'income'].includes(type)) {
        throw new Error('类型必须是 expense 或 income');
    }

    // 找到设置按钮的位置
    const settingsIndex = categories.value[type].findIndex(cat => cat.id === 999);

    if (settingsIndex !== -1) {
        // 在设置按钮之前插入新分类
        categories.value[type].splice(settingsIndex, 0, category);
    } else {
        // 如果没有设置按钮，就添加到末尾
        categories.value[type].push(category);
    }

    saveCategories();
};

// 删除分类（可以删除基础分类和自定义分类，但不能删除设置按钮）
const removeCategory = (type, categoryId) => {
    if (!['expense', 'income'].includes(type)) {
        throw new Error('类型必须是 expense 或 income');
    }

    // 不能删除设置按钮
    const isSettings = categoryId === 999;

    if (isSettings) {
        throw new Error('设置按钮不能删除');
    }

    const index = categories.value[type].findIndex(cat => cat.id === categoryId);
    if (index !== -1) {
        categories.value[type].splice(index, 1);

        // 如果是基础分类，记录到被删除的基础分类列表中
        const isBaseExpense = baseExpenseCategories.some(cat => cat.id === categoryId);
        const isBaseIncome = baseIncomeCategories.some(cat => cat.id === categoryId);

        if (isBaseExpense || isBaseIncome) {
            saveDeletedBaseCategories(type, categoryId);
        }

        saveCategories();
    }
};

// 重置所有分类（恢复被删除的基础分类）
const resetAllCategories = () => {
    // 清除被删除的基础分类记录
    localStorage.removeItem('deletedBaseExpenseCategories');
    localStorage.removeItem('deletedBaseIncomeCategories');
    localStorage.removeItem('customExpenseCategories');
    localStorage.removeItem('customIncomeCategories');

    // 重新加载分类
    categories.value = loadCategories();
};

// 确保设置按钮在最后（修复数据）
const ensureSettingsAtEnd = () => {
    ['expense', 'income'].forEach(type => {
        const settingsIndex = categories.value[type].findIndex(cat => cat.id === 999);
        if (settingsIndex !== -1 && settingsIndex !== categories.value[type].length - 1) {
            // 如果设置按钮不在最后，移动到末尾
            const settingsItem = categories.value[type].splice(settingsIndex, 1)[0];
            categories.value[type].push(settingsItem);
        }
    });
    saveCategories();
};

// 初始化时确保设置按钮在最后
ensureSettingsAtEnd();

export {
    categories,
    saveCategories,
    addCustomCategory,
    removeCategory,
    baseExpenseCategories,
    baseIncomeCategories,
    settingsCategory,
    ensureSettingsAtEnd,
    resetAllCategories
};